package com.gexiaobao.pigeon.ui.activity.supervise

import android.os.Bundle
import android.view.View
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.initClose
import com.gexiaobao.pigeon.databinding.ActivitySigningBinding
import com.gexiaobao.pigeon.viewmodel.MainViewModel

/**
 * @Author      : hxw
 * @Date        : 2024/4/12 15:51
 * @Describe    : 签约
 */
class ActivitySigning : BaseActivity<MainViewModel, ActivitySigningBinding>() {
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeBar.toolbar.initClose("签约") {
            finish()
        }
        val url = intent?.getStringExtra("url").toString()
        initWebView(url)
    }

    private fun initWebView(url: String) {
        mDatabind.webView.loadUrl(url)
        val webSettings = mDatabind.webView.settings
        webSettings.userAgentString += "Android-Pigeon"
        webSettings.javaScriptEnabled = true//允许使用js
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE//不使用缓存，只从网络获取数据.
        // 自适应屏幕
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.loadWithOverviewMode = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true//设置js可以直接打开窗口，如window.open()，默认为false
        webSettings.loadWithOverviewMode = false//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW//加载https和http混合模式
        mDatabind.webView.webChromeClient = webChromeClient
    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {

        override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
            return super.onJsAlert(view, url, message, result)
        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
        }

        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (mDatabind.progressBar != null) {
                mDatabind.progressBar.visibility = View.VISIBLE
                mDatabind.progressBar.progress = newProgress
                if (newProgress == 100) {
                    mDatabind.progressBar.visibility = View.GONE
                }
            }
        }
    }

    override fun onDestroy() {
        mDatabind.webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
        mDatabind.webView.clearHistory()
        mDatabind.webView.destroy()
        super.onDestroy()
    }
}